const enterpriseVue = new Vue({
    el: "#app",
    data() {
      return {
        pickerOptions: pickerOptions,
        rules: {
          Start_Date: [
            { required: true, message: "请选择开始时间", trigger: "blur" },
          ],
          End_Date: [
            { required: true, message: "请选择开始时间", trigger: "blur" },
          ],
        },
        Article_SerialNumber: [
          { required: true, message: "请选择商品", trigger: "change" },
        ],
        Specifications_Name: [
          { required: true, message: "请选择规格", trigger: "change" },
        ],
        Distribute: [
          { required: true, message: "请输入分配数量", trigger: "blur" },
        ],
        Sales_Unit_Price: [
          { required: true, message: "请输入销售单价", trigger: "blur" },
        ],
        store: [],
        column: [],
        shop: [],
        specs: [],
        isDisabled: true,
        type: "",
        //导入属性
        fileList: [],
        sales_unitprice: {},
        Store_SerialNumber: [],
        ShopColumn_Id: [],
        Start_Date: "",
        End_Date: "",
        Distribute: "",
        Enterprise: [],
        // 获取到的栏目数组
        ColumnData: [],
        dialogVisible: false,
        always: "0",
        Coupon_Scheme_Type_options: [
          {
            value: 0,
            label: "签到",
          },
          {
            value: 1,
            label: "购买商品赠送",
          },
          {
            value: 2,
            label: "兑换码",
          },
        ],
        form: {
          //优惠券
          Coupon_Scheme_SerialNumber: "",
          Coupon_Scheme_Name:'', // 优惠券方案名称
          Start_Date: "",     //  开始时间
          End_Date: "",      // 结束时间
          Expiration_Date: "",  //  过期时间
          Coupon_Scheme_Rule:"0", // 优惠券规则
          Coupon_Scheme_Type: "",  // 优惠券类型
          Total_Quantity: "",   // 发放数量 
          Min_Amount: "",    // 最低销售额
          Quantity_Restrictions: "",
          Customer_Restrictions: "",
          Surplus_Quantity: '',
          Receive_Quantity: '',
          Apply_Quantity: '',
          Take_Effect: '',
          Preferential:'',
          Enterprise_Info_SerialNumber: $.cookie("enterprise"),
          Children: {
            coupon_scheme_detail: [],
            coupon_scheme_storescope: [
              {
                //优惠券方案适用店铺
                Coupon_Scheme_StoreScope_SerialNumber: "",
                Coupon_Scheme_SerialNumber: "",
                Store_SerialNumber: "",
              },
            ],
          },
        },
        loading: false,
        tableData: [],
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        total: 1,
        formData:{
          page: 1,			//页数
          limit: 10,		//每页数据条数
          Article_Name: "",
          Category_SerialNumber: "",
          Brand_SerialNumber:'',
        },
        Pic: [],
        brand:[],
        Brand_SerialNumber:'',
        category:[],
        selected: [],
      };
    },
    mounted() {
        const Coupon_Scheme_SerialNumber = sessionStorage.getItem("Coupon_Scheme_SerialNumber")
      this.getData(Coupon_Scheme_SerialNumber);
    },
    computed: {
      Column() {
        return function (name) {
          let obj = this.column.filter((item, index) => {
            return name == item.name;
          })[0];
          return obj.ShopColumn_Id;
        };
      },
      Article() {
        return function (name) {
          let obj = this.shop.filter((item, index) => {
            return name == item.Article_Name;
          })[0];
          return obj.Article_SerialNumber;
        };
      },
      Unit_Price() {
        return function (name) {
          let obj = this.shop.filter((item, index) => {
            return name == item.Article_Name;
          })[0];
          return obj.Unit_Price;
        };
      },
      formatTime() {
        return function (time) {
          let d = new Date(time);
          let year = d.getFullYear();
          let month = d.getMonth() + 1;
          let day = d.getDate();
          let hour = d.getHours();
          let minute = d.getMinutes();
          let second = d.getSeconds();
          if (month < 10) {
            month = "0" + month;
          }
          if (day < 10) {
            day = "0" + day;
          }
          if (hour < 10) {
            hour = "0" + hour;
          }
          if (minute < 10) {
            minute = "0" + minute;
          }
          if (second < 10) {
            second = "0" + second;
          }
          return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        };
      },
    },
    methods: {
      onSerach() {		//查询方法
        this.getList(this.formData)
      },
      handleSizeChange(val) {
        this.form.page = 1;
        this.form.limit = val;
        this.getList(this.formData)
      },
      handleCurrentChange(val) {
        this.form.page = val;
        this.getList(this.formData)
      },
      getData(Coupon_Scheme_SerialNumber) {
        let _this = this;
        $.ajax({
          type: "POST",
          url: DomainName + '/getSubtableInquiryOriginal?token=' + $.cookie("token"),
          data: {
            JSONObject:JSON.parse({coupon_scheme:{coupon_scheme_detail:{},coupon_scheme_storescope:{}}}),
            Primary_Key:Coupon_Scheme_SerialNumber
          },
          success: function (res) {
            // res = res.filter(function (item) {
            //   return item.Row_Status != "1";
            // });
            // for (let i = 0; i < res.length; i++) {
            //   _this.store.push(res[i]);
            // }
            console.log(res);
          },
          complete: function (XMLHttpRequest) {
            _this.loading = false;
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href =
                "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json",
        });
      },
      getList(data) {
        let _this = this
        $.ajax({
          type: 'POST',
          data,
          url: DomainName + '/getArticleInfo3Action?token=' + $.cookie("token"),
          success: function (data) {
            _this.tableData = data.tableData || [];
            _this.tableData.forEach(item => {
              item.loading = false;
              item.srcList = [DomainIMG + item.Picture_URL];
            });
            _this.total = parseInt(data.limit) || 0;
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = '../../../' + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json"
        });
      },
      //店铺接口
      getShop() {
        const _this = this;
        $.ajax({
          type: "POST",
          url: DomainName + "/getStoreAction?token=" + $.cookie("token"),
          data: {
            Data: JSON.stringify(_this.ColumnData),
          },
          success: function (res) {
            // res = res.filter(function (item) {
            //   return item.Row_Status != '1'
            // })
            // for (let i = 0; i < res.length; i++) {
            //   _this.store.push(res[i]);
            // }
            if (res.Status == "success") {
              _this.store = res.Data;
            }
  
            console.log(res);
          },
          complete: function (XMLHttpRequest) {
            _this.loading = false;
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href =
                "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json",
        });
      },
      ChangeRadio(e, index) {
        console.log(e, index);
        this.form.Children.sales_unitprice_detail[index].Article_SerialNumber =
          "";
        this.form.Children.sales_unitprice_detail[
          index
        ].Article_Specifications_SerialNumber = "";
        this.form.Children.sales_unitprice_detail[index].Unit_Price = "";
        this.form.Children.sales_unitprice_detail[index].Net_Content = "";
        this.form.Children.sales_unitprice_detail[index].Sales_Unit_Price = "";
        this.form.Children.sales_unitprice_detail[index].specs = [];
        this.form.Children.sales_unitprice_detail[index].isWarehouse = [];
        this.form.Children.sales_unitprice_detail[index].Warehouse = [];
      },
      validateEnd_Date(rule, value, callback) {
        if (+new Date(value) < +new Date(this.form.Start_Date)) {
          callback(new Error("结算时间不能小于开始时间"));
        } else {
          callback();
        }
      },
      Change_Unit_Price(index, Sign) {
        let str =
          this.form.Children.sales_unitprice_detail[index].Article_SerialNumber;
        this.form.Children.sales_unitprice_detail[
          index
        ].Article_Specifications_SerialNumber = "";
        let _this = this;
        $.ajax({
          type: "POST",
          url: DomainName + "/SpecificationsIDAction",
          data: {
            Article_SerialNumber: str,
            token: $.cookie("token"),
          },
          success: function (res) {
            _this.form.Children.sales_unitprice_detail[index].specs = res;
            console.log(res);
            _this.isDisabled = false;
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href =
                "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json",
        });
        if (Sign == "有货货主") {
          $.ajax({
            url: DomainName + "/getWarehouseGoodsID?token=" + $.cookie("token"),
            type: "POST",
            data: {
              Article_SerialNumber: str,
            },
            success: function (res) {
              console.log(res);
              if (res.Data.length > 0) {
                _this.form.Children.sales_unitprice_detail[index].Warehouse =
                  res.Data;
              }
            },
          });
        }
      },
      Change_Specifications_Name(index) {
        let str =
          this.form.Children.sales_unitprice_detail[index]
            .Article_Specifications_SerialNumber;
        console.log(str);
        console.log(this.form.Children.sales_unitprice_detail[index].specs[0]);
        for (
          let i = 0;
          i < this.form.Children.sales_unitprice_detail[index].specs.length;
          i++
        ) {
          console.log(
            this.form.Children.sales_unitprice_detail[index].specs[i]
              .Article_Specifications_SerialNumber
          );
          if (
            this.form.Children.sales_unitprice_detail[index].specs[i]
              .Article_Specifications_SerialNumber == str
          ) {
            this.form.Children.sales_unitprice_detail[index].Net_Content =
              this.form.Children.sales_unitprice_detail[index].specs[
                i
              ].Net_Content;
            this.form.Children.sales_unitprice_detail[index].Unit_Price =
              this.form.Children.sales_unitprice_detail[index].specs[
                i
              ].Unit_Price;
          }
        }
      },
      // Change_Column_Type() {
      //   if(this.form.Activity=='0'){
      //     this.column.forEach((item, index) => {
      //       item.options.forEach(item1 => {
      //         this.form.Children.sales_unitprice_column.forEach
      //         (item2 => {
      //           if (index == 0 && item2.ShopColumn_Id == item1.ShopColumn_Id) {
      //             item2.Column_Type = '0'
      //           } else if (index == 1 && item2.ShopColumn_Id == item1.ShopColumn_Id) {
      //             item2.Column_Type = '1'
      //           }
      //         })
      //       })
      //     })
      //   }else if (this.form.Activity=='1'){
      //     this.form.Children.sales_unitprice_column.forEach(item => {
      //       item.Column_Type = '1'
      //     })
      //   }
      // },
      // 获取所属栏目的选中值
      fetch(item) {
        console.log("获取的数据", item.App_ID);
        if (
          !this.ColumnData.some((App_ID) => {
            App_ID == item.App_ID;
          })
        ) {
          this.ColumnData.push(item.App_ID);
        }
        console.log(this.ColumnData);
        this.getShop();
      },
      Automatic(item, Store_SerialNumber, Start_Date, End_Date, time) {
        //一天毫秒数
        let TimeDays = 1000 * 60 * 60 * 24;
        if (+new Date(End_Date) <= +new Date(time)) {
          //若结算时间小于次日补货时间
          item.Children.sales_unitprice_stock.push({
            Sales_Unit_Price_Stock_SerialNumber: "",
            Sales_Unit_Price_Detail_SerialNumber: "",
            Store_SerialNumber,
            Start_Date: Start_Date,
            End_Date: End_Date,
            Distribute: parseInt(item.Distribute),
            Stock_Remain: parseInt(item.Distribute),
            Stock_Sell: 0,
          });
        } else {
          //若结算时间大于次日补货时间
          item.Children.sales_unitprice_stock.push({
            Sales_Unit_Price_Stock_SerialNumber: "",
            Sales_Unit_Price_Detail_SerialNumber: "",
            Store_SerialNumber,
            Start_Date: Start_Date,
            End_Date: this.formatTime(+new Date(time) - 1000),
            Distribute: parseInt(item.Distribute),
            Stock_Remain: parseInt(item.Distribute),
            Stock_Sell: 0,
          });
          this.Automatic(
            item,
            Store_SerialNumber,
            time,
            End_Date,
            this.formatTime(+new Date(time) + TimeDays)
          );
        }
      },
      handleSelectionChange(val){
        this.selected = val;
      },
      submitForm(formName) {
        let _this = this;
        console.log(_this.form);
        _this.selected.forEach(item => {
          _this.form.Children.coupon_scheme_detail.push({
              Coupon_Scheme_Detail_SerialNumber: "",
              Coupon_Scheme_SerialNumber: "",
              Article_SerialNumber: item.Article_SerialNumber,
          });
      });
        console.log('coupon_scheme_detail',this.form.Children.coupon_scheme_detail);
        this.$refs[formName].validate((valid) => {
          if (valid) {
            _this.loading = true;
            console.log(_this.form);
            $.ajax({
              url: DomainName + "/getBatchAddAction",
              type: "POST",
              data: {
                tableName:'coupon_scheme',
                Data: JSON.stringify([_this.form]),
                token: $.cookie("token"),
              },
              success: function (res) {
                if (res.Status === "success") {
                  _this.$message.success("操作成功");
                  window.location.href = "./Coupon.html";
                } else {
                  _this.$message.error("操作失败，请稍后再试");
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试");
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false;
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href =
                    "../../../../" +
                    XMLHttpRequest.getResponseHeader("CONTENTPATH");
                }
              },
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      onExcel() {
        this.dialogVisible = true;
      },
      add_sales_unitprice_storescope() {
        this.form.Children.sales_unitprice_storescope.push({
          //销售价格单适用店铺
          Sales_Unit_Price_StoreScope_SerialNumber: "",
          Sales_Unit_Price_SerialNumber: "",
          Store_SerialNumber: "",
        });
      },
      remove_sales_unitprice_storescope() {
        if (this.form.Children.sales_unitprice_storescope.length > 1) {
          this.form.Children.sales_unitprice_storescope.pop();
        } else {
          this.$message({
            message: "不能在删除了",
            type: "warning",
          });
        }
      },
      add_sales_unitprice_column() {
        this.form.Children.sales_unitprice_column.push({
          //栏目
          Sales_Unit_Price_Column_SerialNumber: "",
          Sales_Unit_Price_SerialNumber: "", //单价流水号
          ShopColumn_Id: "", //栏目流水号
          Column_Type: "", //栏目属性
        });
      },
      remove_sales_unitprice_column() {
        if (this.form.Children.sales_unitprice_column.length > 1) {
          this.form.Children.sales_unitprice_column.pop();
        } else {
          this.$message({
            message: "不能在删除了",
            type: "warning",
          });
        }
      },
      add_sales_unitprice_detail() {
        this.form.Children.sales_unitprice_detail.push({
          //销售价格单明细
          Sales_Unit_Price_Detail_SerialNumber: "",
          Sales_Unit_Price_SerialNumber: "",
          Article_SerialNumber: "",
          Article_Specifications_SerialNumber: "",
          Unit_Price: "",
          Sales_Unit_Price: "",
          Sign: "无货货主",
          Distribute: "",
          Net_Content: "",
          specs: [],
          Warehouse: [],
          Children: {
            sales_unitprice_stock: [],
          },
        });
      },
      remove_sales_unitprice_detail() {
        if (this.form.Children.sales_unitprice_detail.length > 1) {
          this.form.Children.sales_unitprice_detail.pop();
        } else {
          this.$message({
            message: "不能在删除了",
            type: "warning",
          });
        }
      },
      beforeRemove() {
        this.fileList.pop();
        this.tableData = [];
      },
      uploadDetails(file) {
        this.fileList.push({
          name: file.name,
          url: file.type,
        });
        const _this = this;
        var reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = function (e) {
          var data = e.target.result;
          var wb = XLSX.read(data, {
            type: "binary", //以二进制的方式读取
          });
          var sheet0 = wb.Sheets[wb.SheetNames[0]]; //sheet0代表excel表格中的第一页
          var json = XLSX.utils.sheet_to_json(sheet0); //利用接口实现转换。
          console.log(json);
          let arr = [];
          json.forEach((item) => {
            let Article = _this.isShop(item["品名"]);
            let Abnormal = [Article.abnormal];
            arr.push({
              Sales_Unit_Price_Detail_SerialNumber: "",
              Sales_Unit_Price_SerialNumber: "",
              Article_Specifications_SerialNumber: "",
              Article_SerialNumber: Article.Article_SerialNumber,
              Unit_Price: item["原售价"],
              Sales_Unit_Price: item["现售价"],
              Sign: item["有/无货货主"],
              Distribute: item["数量"],
              Abnormal: !Abnormal.some((item) => item == false),
              Children: {
                sales_unitprice_stock: [],
              },
            });
          });
          _this.tableData = arr;
        };
      },
      isShop(str) {
        if (this.shop.some((item) => item.Article_Name == str)) {
          return {
            Article_SerialNumber: this.shop.filter(
              (item) => item.Article_Name == str
            )[0].Brand_SerialNumber,
            abnormal: true,
          };
        } else {
          return {
            Article_SerialNumber: "异常数据(未找到" + str + ")",
            abnormal: false,
          };
        }
      },
      submitForm1() {
        let _this = this;
        _this.loading = true;
        //无货货主商品自动按照执行天数，生成货物
        let sales_unitprice_storescope = [];
        let sales_unitprice_column = [];
        var reg = RegExp(/C1/);
        this.Store_SerialNumber.forEach((item) => {
          sales_unitprice_storescope.push({
            Sales_Unit_Price_StoreScope_SerialNumber: "",
            Sales_Unit_Price_SerialNumber: "",
            Store_SerialNumber: item,
          });
        });
        this.ShopColumn_Id.forEach((item) => {
          sales_unitprice_column.push({
            Sales_Unit_Price_Column_SerialNumber: "",
            Sales_Unit_Price_SerialNumber: "", //单价流水号
            ShopColumn_Id: item,
            Column_Type: reg.test(item) ? "1" : "0", //栏目属性
          });
        });
        let obj = {
          Sales_Unit_Price_SerialNumber: "",
          Start_Date: this.Start_Date,
          End_Date: this.End_Date,
          Row_Status: "2",
          Enterprise_Info_SerialNumber: $.cookie("enterprise"),
          Children: {
            sales_unitprice_detail: [],
            sales_unitprice_storescope,
            sales_unitprice_column,
          },
        };
        this.getAddAction(this.tableData, obj);
      },
      getAddAction(data, obj) {
        const _this = this;
        if (data.length > 2) {
          let arr1 = data.filter((item, index) => index < 2);
          let arr2 = data.filter((item, index) => index >= 2);
          obj.Children.sales_unitprice_detail = arr1;
          console.log(obj);
          console.log(arr1);
          console.log(arr2);
          this.Add(obj, () => {
            _this.getAddAction(arr2, obj);
          });
        } else {
          this.Add(data, () => {
            _this.$message.success("提交成功");
            _this.loading = false;
            window.location.href = "./Goods.html";
          });
        }
      },
      Add(arr, callback) {
        const _this = this;
        let TimeDays = 1000 * 60 * 60 * 24;
        let time = `${arr.Start_Date.substring(0, 10)} ${this.always}`;
        if (+new Date(time) < +new Date(arr.Start_Date)) {
          time = this.formatTime(+new Date(time) + TimeDays);
        }
        arr.Children.sales_unitprice_storescope.forEach(function (item1, index) {
          arr.Children.sales_unitprice_detail.forEach(function (item, index) {
            if (item.Sign == "无货货主") {
              _this.Automatic(
                item,
                item1.Store_SerialNumber,
                arr.Start_Date,
                arr.End_Date,
                time
              );
            }
          });
        });
        $.ajax({
          type: "POST",
          url: DomainName + "/getAddAction?token=" + $.cookie("token"),
          data: {
            Data: JSON.stringify({ sales_unitprice: arr }),
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href =
                XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          success: function (Result) {
            if (Result.Status == "success") {
              console.log("提交成功");
              callback();
            }
          },
          error: function () {
            _this.$message.error("操作失败，请稍后再试");
          },
          dataType: "json",
        });
      },
      Filter(i, row) {
        if (i == 2) {
          this.tableData = this.tableData.filter(
            (item) =>
              item.Abnormal && item.Distribute > 0 && item.Sales_Unit_Price > 0
          );
          this.$message.success("已筛选掉异常数据");
        }
      },
      tableCellStyle({ row, column, rowIndex, columnIndex }) {
        if (!row.Abnormal) return { backgroundColor: "#E6A23C" };
      },
    },
  });
  